package com.nettylearning.base.netty.io.buffer;

import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author vince
 * @date 2021/7/17 7:47
 * @description 7. 内存映射（I/O映射缓冲区）
 * @Version 1.0
 */
public class MappedBuffer {
    static private final int start = 0;
    static private final int size = 1024;

    static public void main(String args[]) throws Exception {
        RandomAccessFile raf = new RandomAccessFile("D://test.txt", "rw");
        FileChannel fc = raf.getChannel();

        // 把缓冲区跟文件系统进行一个映射关系
        // 只要操作缓冲区里面的内容，文件内容也会跟着改变
        MappedByteBuffer mappedByteBuffer = fc.map(FileChannel.MapMode.READ_WRITE, start, size);
        mappedByteBuffer.put(0, (byte) 97);
        mappedByteBuffer.put(1023, (byte) 122);

        raf.close();
    }
}
